import React, { memo, useRef ,useState ,createContext,useEffect} from 'react'
import { shallowEqual, useDispatch, useSelector } from 'react-redux'
import { NavLink } from 'react-router-dom'
import {
  changeCurrentLyricIndexAction
} from '../store/actionCreator'

import Control from './c-cpns/control'
import PlayInfo from './c-cpns/play-info'
import Operator from './c-cpns/operator'

import { getPlayUrl } from '@/utils/format-utils'
import{ PlayerbarWrapper } from './style'
import { message } from 'antd'

export const AudioContext = createContext();

function FAppPlayerBar(){

  const [currentTime, setCurrentTime] = useState(0) // 用于保存当前播放的时间
  const [isChanging, setIsChanging] = useState(false) // 是否正在滑动

  // redux hook
  const dispatch = useDispatch()

  const {
    currentSong,
    playStatus,
    lyricList = [],
    currentLyricIndex,
  } = useSelector(
    (state) => ({
      currentSong: state.getIn(['player', 'currentSong']),
      playStatus: state.getIn(['player', 'playStatus']),
      lyricList: state.getIn(['player', 'lyricList']),
      currentLyricIndex: state.getIn(['player', 'currentLyricIndex']),
    }),
    shallowEqual
  )

  const audioRef = useRef()

  useEffect(() => {
    audioRef.current.src = getPlayUrl(currentSong.id)
    // 设置音量
    audioRef.current.volume = 0.5
  }, [currentSong])


  // 切换歌曲时播放音乐
  useEffect(() => {
    console.log(playStatus)
    playStatus ? audioRef.current.play(): audioRef.current.pause()
  }, [playStatus])



  function timeUpdate(e){
    let currentTime = e.target.currentTime
    if (!isChanging) {
      setCurrentTime(currentTime * 1000)
    }
    // 获取当前播放歌词
    let i = 0 //用于获取歌词的索引
    // 2.遍历歌词数组
    for (; i < lyricList.length; i++) {
      const item = lyricList[i]
      if (currentTime * 1000 < item.totalTime) {
        // 4.跳出循环
        break
      }
    }
    // 对dispatch进行优化,如果index没有改变,就不进行dispatch
    if (currentLyricIndex !== i - 1) {
      dispatch(changeCurrentLyricIndexAction(i - 1))
    }

    // 展示歌词
    const lyricContent = lyricList[i - 1] && lyricList[i - 1].content
    lyricContent &&
      message.open({
        key: 'lyric',
        content: lyricContent,
        duration: 0,
        className: 'lyric-css',
      })
  }


  return (
    <PlayerbarWrapper className="sprite_player">
      <div  className="w980 content">
        <Control  />
        <AudioContext.Provider  value = {{ setCurrentTime ,setIsChanging}}>
          <PlayInfo audioRef ={audioRef}  currentTime={currentTime} isChanging={isChanging} />
        </AudioContext.Provider>
        <Operator />
      </div>
      <audio
        id="audio"
        ref={audioRef}
        onTimeUpdate={timeUpdate}
        preload="auto"
      />
    </PlayerbarWrapper>
  )
}

export default memo(FAppPlayerBar)